const controllers = {};
const uuid = require("uuid");
const moment = require("moment");

const modules = require("../models/index");

const axios = require("axios");
/**
 * 记录圣诞树日志
 */
controllers.record = async (request, response) => {
  try {
    let clientIP =
      request.headers["x-real-ip"] ||
      request.headers["x-forwarded-for"] ||
      request.ip;
    const addressRes = await axios({
      method: "get",
      url: "https://apis.map.qq.com/ws/location/v1/ip",
      params: {
        key: "7K2BZ-Q7D6P-RQZDX-LZTLM-SIAPT-ODFXQ",
        ip: clientIP,
      },
    });
    let ip = await modules.readRecord(clientIP);
    let form = {};
    if (ip.length > 0) {
      form = {
        id: ip[0].id,
        time: moment().format("YYYY-MM-DD HH:mm:ss"),
        ip: ip[0].ip,
        address: ip[0].address,
      };
      await modules.updateRecord(form);
    } else {
      let address =
        addressRes.data &&
          addressRes.data.result &&
          addressRes.data.result.ad_info
          ? addressRes.data.result.ad_info
          : "获取位置失败";
      address = address.nation
        ? `${address.nation},${address.province},${address.city},${address.district}`
        : "获取位置失败";
      form = {
        id: uuid.v4().replace(/-/g, ""),
        time: moment().format("YYYY-MM-DD HH:mm:ss"),
        ip: clientIP,
        address: address,
      };
      await modules.record(form);
    }

    response.send({
      code: 200,
      data: {
        time: moment().format("YYYY-MM-DD HH:mm:ss"),
        ip: form.ip,
        address: form.address,
      },
      message: "success",
    });
  } catch (error) {
    response.send({
      code: 500,
      msg: error.message || error,
    });
  }
};

/**
 * 记录水电
 */
controllers.add = async (request, response) => {
  const body = request.body;
  const uid = request.headers.auth;
  if (uid && body.recordType && body.insertType && body.insertDate) {
    try {
      let form = {
        id: uuid.v4().replace(/-/g, ""),
        u_id: uid,
        record_type: body.recordType,
        insert_type: body.insertType,
        amount: body.amount,
        balance: body.balance,
        insert_date: body.insertDate,
        create_date: moment().format("YYYY-MM-DD HH:mm:ss"),
      };
      await modules.add(form);

      response.send({
        code: 200,
        data: form,
        message: "success",
      });
    } catch (error) {
      response.send({
        code: 500,
        msg: error.message || error,
      });
    }
  } else {
    response.status(400).send({
      code: 400,
      msg: "缺少参数",
    });
  }
};

/**
 * 获取记录
 */
controllers.list = async (request, response) => {
  try {
    const query = request.query;
    const uid = request.headers.auth;
    const list = await modules.list(uid, query);
    // 计算电费
    const E = list.filter((item) => item.recordType == "1");
    let REQ = 0;
    let RET = 0;
    let ETU = 0;
    let EAU = 0;
    if (E.length > 0) {
      for (let i = 0; i < E.length; i++) {
        const item = E[i];
        if (item.insertType == "1") {
          RET += item.amount;
          REQ += item.balance - (E[i + 1] ? E[i + 1].balance : 0);
        }
      }
      ETU = Math.abs(E[0].balance - E[E.length - 1].balance - REQ);
      EAU = ETU / timeDifference(E[0].insertDate, E[E.length - 1].insertDate) || 0;
      if (ETU === 0) {
        EAU = 0;
      } else if (timeDifference(E[0].insertDate, E[E.length - 1].insertDate) === 0) {
        EAU = ETU;
      }
    }
    // 计算水费
    const W = list.filter((item) => item.recordType == "2");
    let RWQ = 0;
    let RWT = 0;
    let WTU = 0;
    let WAU = 0;
    if (W.length > 0) {
      for (let i = 0; i < W.length; i++) {
        const item = W[i];
        if (item.insertType == "1") {
          RWT += item.amount;
          RWQ += item.balance - (W[i + 1] ? W[i + 1].balance : 0);
        }
      }
      WTU = Math.abs(W[0].balance - W[W.length - 1].balance - RWQ);
      WAU = WTU / timeDifference(W[0].insertDate, W[W.length - 1].insertDate) || 0;
      if (WTU === 0) {
        WAU = 0;
      } else if (timeDifference(W[0].insertDate, W[W.length - 1].insertDate) === 0) {
        WAU = WTU;
      }
    }
    response.send({
      code: 200,
      data: {
        list: list,
        summary: {
          electricity: {
            totalUse: Number(ETU.toFixed(2)),
            averageUsage: Number(EAU.toFixed(2)),
            totalRecharge: Number(RET.toFixed(2)),
          },
          water: {
            totalUse: Number(WTU.toFixed(2)),
            averageUsage: Number(WAU.toFixed(2)),
            totalRecharge: Number(RWT.toFixed(2)),
          }
        }
      },
      message: "success",
    });
  } catch (error) {
    response.send({
      code: 500,
      msg: error.message || error,
    });
  }
};

function timeDifference(A, B) {
  // 将日期字符串转换为 Date 对象
  const dateA = new Date(A);
  const dateB = new Date(B);
  // 计算两个日期之间的时间差（以毫秒为单位）
  const timeDifference = Math.abs(dateB - dateA);
  // 将时间差转换为天数
  const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
  const daysDifference = Math.floor(timeDifference / oneDay);
  return daysDifference;
}

module.exports = controllers;
